<?php

namespace app\data\controller\record;

use app\data\service\CityUserRelationService;
use think\admin\Controller;

/**
 * 城市归属管理
 * Class CityRelation
 * @package app\data\controller\base
 */
class CityRelation extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'data_city_relation';

    /**
     * 城市负责人列表
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '城市归属管理';

        $query = $this->_query($this->table);
        $query->like('from_city,to_city')->equal('status')->dateBetween('create_at');

        if (!empty($name = $this->request->request('name', ''))) {
            $uuids = $this->app->db->name('work_user')->where('name', 'like', "%{$name}%")->field('id,name')->select()->toArray();
            $uuids = array_column($uuids, 'id');

            $cityRelationIds = $this->app->db->name('data_city_user_relation')->whereIn('uuid', $uuids)->select()->toArray();
            $cityRelationIds = array_column($cityRelationIds, 'city_relation_id');

            $query->whereIn('id', $cityRelationIds);
        }

        $query->order('status desc, id desc')->page();
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        $cityUserTree = CityUserRelationService::instance()->getCityUserTree();
        foreach ($cityUserTree as $cityUser) {
            $mapId2NameText[$cityUser['id']] = implode(' | ', array_column($cityUser['users'], 'name'));
        }

        foreach ($data as &$item) {
            $item['name_text'] = $mapId2NameText[$item['id']] ?? '';
            $item['uuid_docking_name'] = CityUserRelationService::instance()->getUuidDockingNameByProvinceAndCity($item['from_province'], $item['from_city'])['uuid_docking_name'] ?? '';
        }
    }

    /**
     * 添加城市归属
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $this->title = '添加城市归属';
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑城市归属
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->_form($this->table, 'form');
    }

    /**
     * 表单数据处理
     * @param array $data
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isGet()) {
            if (!empty($data['id'])) {
                $this->data = CityUserRelationService::instance()->getRelation($data['id']);
            }

            if (empty($data['from_province']) || empty($data['from_city'])) {
                $this->uuid_docking_name = '';
            } else {
                $uuidDocking = CityUserRelationService::instance()->getUuidDockingNameByProvinceAndCity($data['from_province'], $data['from_city']);
                $this->uuid_docking_name = $uuidDocking['uuid_docking_name'];
            }

        }
        if ($this->request->isPost()) {
            if (empty($data['to_city'])) {
                $this->error('归属城市不能为空');
            }

            if (!empty($data['uuids'])) {
                if (count($data['uuids']) != count(array_unique($data['uuids']))) {
                    $this->error('员工选择出现重复');
                }
            }

            foreach ($data['uuids'] ?? [] as $uuid) {
                if (empty($uuid)) {
                    $this->error('员工不能为空');
                }
            }

            if (empty($data['from_city'])) {
                if (!empty($data['id'])) {
                    $maps[] = [
                        ['id', '<>', $data['id']],
                        ['from_province', '=', $data['from_province']],
                    ];
                } else {
                    $maps[] = [
                        ['from_province', '=', $data['from_province']],
                    ];
                }
            } else {
                if (!empty($data['id'])) {
                    $maps[] = [
                        ['id', '<>', $data['id']],
                        ['from_province', '=', $data['from_province']],
                        ['from_city', '=', $data['from_city']],
                    ];
                    $maps[] = [
                        ['id', '<>', $data['id']],
                        ['from_province', '=', $data['from_province']],
                        ['from_city', '=', ''],
                    ];
                } else {
                    $maps[] = [
                        ['from_province', '=', $data['from_province']],
                        ['from_city', '=', $data['from_city']],
                    ];
                    $maps[] = [
                        ['from_province', '=', $data['from_province']],
                        ['from_city', '=', ''],
                    ];
                }
            }

            foreach ($maps as $map) {
                $hasOther = $this->app->db->name($this->table)->where($map)->findOrEmpty();
                if ($hasOther) {
                    $this->error('该地区已经存在归属');
                }
            }
        }
    }

    /**
     * 表单结果处理
     * @param boolean $state
     */
    protected function _form_result(bool $state, $data)
    {
        if ($state) {

            if (empty($data['id'])) {
                $data['id'] = $this->app->db->name($this->table)->order('id desc')->findOrEmpty();
                $data['id'] = $data['id']['id'] ?? 0;
            }

            foreach ($data as $key => $datum) {
                if (strpos($key, 'group_power_status_') !== false) {
                    $data['group_power_status'][] = $datum;
                }
                if (strpos($key, 'online_status_') !== false) {
                    $data['online_status'][] = $datum;
                }

            }

            foreach ($data['uuids'] as $user) {
                $userId = explode('#', $user);
                $userIds[] = $userId[0] ?? 0;
            }

            // 保存城市员工关联
            CityUserRelationService::instance()->save($data['id'], $userIds ?? [], $data['percentages'] ?? [], $data['limits'] ?? [], $data['group_power_status'] ?? [], $data['online_status'] ?? []);

            $this->success('内容保存成功！', 'javascript:history.back()');
        }
    }

    /**
     * 删除城市归属
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

    /**
     * 修改状态
     * @throws \think\db\exception\DbException
     */
    public function state()
    {
        $this->_save($this->table, $this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 默认城市负责人配置
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function config()
    {
        $this->skey = 'DefaultCityUuid';
        $this->title = '默认城市负责人配置';
        if ($this->request->isGet()) {
            $this->users = $this->app->db->name('work_user')->where('authorize', 'like', "%3%")->order('id desc')->select()->toArray();
            $this->data = sysdata($this->skey);
            $this->fetch('config');
        } else {

            $data = $this->request->post();
            if (empty($data['uuid'])) {
                $this->error('城市负责人不能为空');
            }

            sysdata($this->skey, $data['uuid']);

            $this->success('配置修改成功');
        }
    }

    /**
     * 获取调度员
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDockingUuid()
    {
        $data = $this->_vali([
            'from_province.require' => '省不能为空！',
            'from_city.require' => '市不能为空！',
        ]);

        $response = CityUserRelationService::instance()->getUuidDockingNameByProvinceAndCity($data['from_province'], $data['from_city']);

        $this->success('获取调度员成功', [
            'id' => $response['id'],
            'uuid_docking_name' => $response['uuid_docking_name'],
        ]);
    }

    /**
     * 城市默认归属配置(已废弃)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function configBak()
    {
        $this->skey = 'DefaultCityRelation';
        $this->title = '城市负责人配置';
        $this->_sysdata();
    }

    /**
     * 配置数据处理(已废弃)
     * @param string $tpl 模板文件
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function _sysdata(string $tpl = '')
    {
        if ($this->request->isGet()) {
            $this->users = $this->app->db->name('work_user')->where('authorize', 'like', "%2%")->order('id desc')->select()->toArray();
            $this->data = sysdata($this->skey);
            if (!isset($this->data['list'])) {
                $this->data['list'] = [];
            }
            $this->fetch($tpl);
        } else {

            $data = $this->request->post();
            if (empty($data['uuid'])) {
                $this->error('对接人不能为空');
            }

            foreach ($data as $key => $datum) {
                if (strpos($key, 'group_power_status') !== false) {
                    $data['group_power_status'][] = $datum;
                }

                if (strpos($key, 'online_status') !== false) {
                    $data['online_status'][] = $datum;
                }
            }

            foreach ($data['percentages'] ?? [] as $key => $percentage) {
                $uuids = explode('#', $data['uuids'][$key]);
                $data['list'][] = [
                    'limit' => $data['limits'][$key] ?? 1,
                    'percentage' => $percentage,
                    'id' => $uuids[0],
                    'name' => $uuids[1],
                    'group_power_status' => $data['group_power_status'][$key] ?? 1,
                    'online_status' => $data['online_status'][$key] ?? 1,
                ];
            }

            sysdata($this->skey, $data);
            $this->success('配置修改成功', 'javascript:history.back()');
        }
    }
}